package com.zjw.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjw.shortlink.admin.common.biz.user.UserContext;
import com.zjw.shortlink.admin.common.constant.RedisCacheConstant;
import com.zjw.shortlink.admin.common.convention.exception.ClientException;
import com.zjw.shortlink.admin.common.convention.exception.ServiceException;
import com.zjw.shortlink.admin.common.convention.result.Result;
import com.zjw.shortlink.admin.dao.entity.GroupDO;
import com.zjw.shortlink.admin.dao.mapper.GroupMapper;
import com.zjw.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.zjw.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.zjw.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.zjw.shortlink.admin.remote.ShortLinkActualRemoteService;
import com.zjw.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.zjw.shortlink.admin.service.GroupService;
import com.zjw.shortlink.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final RedissonClient redissonClient;
    private final RBloomFilter<String> gidRegisterCachePenetrationBloomFilter;
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;
    @Override
    public void saveGroup(String groupName) {
        saveGroup(UserContext.getUsername(), groupName);
    }

    @Override
    public void saveGroup(String userName, String groupName) {
        RLock lock = redissonClient.getLock(String.format(RedisCacheConstant.LOCK_GROUP_CREATE_KEY, userName));
        lock.lock();
        try {
            LambdaQueryWrapper<GroupDO> queryWrapper = new LambdaQueryWrapper<GroupDO>()
                    .eq(GroupDO::getUsername, userName)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOS = baseMapper.selectList(queryWrapper);
            if(CollUtil.isNotEmpty(groupDOS) && groupDOS.size() == groupMaxNum) {
                throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
            }
            int retryCount = 0;
            int maxRetries = 10;
            String gid = null;
            while(retryCount < maxRetries) {
                gid = RandomGenerator.generateRandom();
                if(!hasGid(gid)) {
                    GroupDO groupDO = GroupDO.builder()
                            .username(userName)
                            .name(groupName)
                            .gid(gid)
                            .sortOrder(0)
                            .build();
                    baseMapper.insert(groupDO);
                    return;
                }
                retryCount++;
            }
            throw new ServiceException("生成分组标识频繁");
        } finally {
            lock.unlock();
        }
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = new LambdaQueryWrapper<GroupDO>()
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder)
                .orderByDesc(GroupDO::getUpdateTime);
        List<ShortLinkGroupRespDTO> groupDOS = BeanUtil.copyToList(baseMapper.selectList(queryWrapper), ShortLinkGroupRespDTO.class);
        List<String> gidList = groupDOS.stream().map(ShortLinkGroupRespDTO::getGid).toList();
        List<ShortLinkGroupCountQueryRespDTO> linkCountList = shortLinkActualRemoteService.listGroupShortLinkCount(gidList).getData();
        groupDOS.forEach(each -> {
            linkCountList.stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst()
                    .ifPresentOrElse(item -> each.setShortLinkCount(item.getShortLinkCount()), () -> each.setShortLinkCount(0));
        });
        return groupDOS;
    }

    @Override
    public void deleteGroup(String gid) {
        LambdaQueryWrapper<GroupDO> queryWrapper = new LambdaQueryWrapper<GroupDO>()
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO, queryWrapper);
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        LambdaQueryWrapper<GroupDO> queryWrapper = new LambdaQueryWrapper<GroupDO>()
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag, 0);
        baseMapper.update(BeanUtil.copyProperties(requestParam, GroupDO.class), queryWrapper);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(item -> {
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(item.getSortOrder())
                    .build();
            LambdaQueryWrapper<GroupDO> queryWrapper = new LambdaQueryWrapper<GroupDO>()
                    .eq(GroupDO::getGid, item.getGid())
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(groupDO, queryWrapper);
        });
    }

    public boolean hasGid(String gid) {
        LambdaQueryWrapper<GroupDO> query = new LambdaQueryWrapper<GroupDO>()
                .eq(GroupDO::getGid, gid)
                // TODO 设置用户名
                .eq(GroupDO::getUsername, UserContext.getUsername());
        GroupDO groupDO = baseMapper.selectOne(query);
        return groupDO != null;
    }

}
